<template>
  <div id="Monitor">
    <div class="panel-default">
      <h3 class="panel-title">漏洞信息</h3>
      <div class="panel-body guard">
        <div class="guard" @click="linkTo('/vulnso', '')">
          <img src="../../assets/images/joinGuard.png" />
          <div>
            <p class="guard-num">{{ eveCount?.totalCount }}</p>
            <p class="guard-title">漏洞总数</p>
          </div>
        </div>
        <div class="guard" @click="linkTo('/vulnso', '')">
          <img src="../../assets/images/newGuard.png" alt="" />
          <div>
            <p class="guard-num">{{ eveCount?.sysCount }}</p>
            <p class="guard-title">系统漏洞</p>
          </div>
        </div>
        <div class="guard" @click="linkTo('/vulnso', 'online')">
          <img src="../../assets/images/onlineGuard.png" alt="" />
          <div>
            <p class="guard-num">{{ eveCount?.dataCount }}</p>
            <p class="guard-title">数据库漏洞</p>
          </div>
        </div>
        <div class="guard" @click="linkTo('/vulnso', 'offline')">
          <img src="../../assets/images/offlineGuard.png" alt="" />
          <div>
            <p class="guard-num">{{ eveCount?.appCount }}</p>
            <p class="guard-title">应用漏洞</p>
          </div>
        </div>
      </div>
    </div>
    <div class="panel-default">
      <h3 class="panel-title">安全风险趋势</h3>
      <div id="echartBox" style="width: 100%; height: 300px"></div>
    </div>

    <div class="panel-default deviceInfo">
      <h3 class="panel-title">系统信息</h3>
      <div class="device-info">
        <ul>
          <li><span>系统名称 : </span><span>系统漏洞与安全风险检索系统</span></li>
          <li>
            <span>系统运行时间 : </span><span>{{ sysTime }}</span>
          </li>
        </ul>
        <div class="demo-progress">
          <div class="chart-box">
            <div ref="cpu" class="chart-style"></div>
            <span class="chart-title">CPU使用率</span>
          </div>
          <div class="chart-box">
            <div ref="memory" class="chart-style"></div>
            <span class="chart-title">内存使用率</span>
          </div>
          <div class="chart-box">
            <div ref="disk" class="chart-style"></div>
            <span class="chart-title">硬盘使用率</span>
          </div>
        </div>
        <div class="device-img">
          <img src="../../assets/images/deviceImg.svg" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ref, reactive, onMounted, onBeforeUnmount, nextTick  } from 'vue'
import { mAxios } from '~/utils/axios/axios.js'
import { eventBus } from '~/utils/common/eventBus.js'
import { useTreeStore } from '~/utils/pinia/tree.js'
import moment from 'moment'
import * as echarts from 'echarts'

const treeStore = useTreeStore()
let $router = useRouter()

let timer = ref()
let scrollTop = ref(0)
let guardInfoList = ref([])
let idx = 5
const scrollStart = () => {
  if (guardInfoList.value.length < 6) return
  clearInterval(timer.value)
  timer.value = setInterval(() => {
    let liHeight = 54 // 每一行的高度
    if (scrollTop.value >= liHeight) {
      idx += 1
      guardInfoList.value.shift()
      if (data.guardInfoList.slice(idx, idx + 1).length == 0) {
        idx = 0
      }
      guardInfoList.value = guardInfoList.value.concat(data.guardInfoList.slice(idx, idx + 1))
      scrollTop.value = 0
    }
    scrollTop.value += 1
  }, 60)
}
const scrollStop = () => {
  clearInterval(timer.value)
}
const mouseScroll = e => {
  if (guardInfoList.value.length < 6) return
  if (e.deltaY > 0) {
    let liHeight = 54 // 每一行的高度
    if (scrollTop.value >= liHeight) {
      idx += 1
      guardInfoList.value.shift()
      if (data.guardInfoList.slice(idx, idx + 1).length == 0) {
        idx = 0
      }
      guardInfoList.value = guardInfoList.value.concat(data.guardInfoList.slice(idx, idx + 1))
      scrollTop.value = 0
    }
    scrollTop.value += 54
  }
}

const deviceStatusHeader = ref(['CVE_ID', '漏洞名称', '描述', '影响产品', '严重程度', '修复建议', '发布时间'])
const data = reactive({
  guardCountFrom: {},
  cpuUsage: null,
  memoryUsage: null,
  diskUsage: null,
  runningTime: '',
  memoryTotal: '',
  diskTotal: '',
  timer: null,
  guardInfoList: []
})

// 处理器、内存、硬盘等图例函数
const cpu = ref()
const memory = ref()
const disk = ref()
const myCharts = {}
const generateRingChart = (chartRef, chartColor, chartData, key) => {
  // if (myCharts[key]) {
  //   myCharts[key].dispose(); // 销毁之前的实例
  // }
  const option = {
    series: [
      {
        type: 'pie',
        radius: ['62%', '91%'],
        avoidLabelOverlap: false,
        label: {
          show: true,
          position: 'center',
          textStyle: {
            rich: {
              val: {
                fontSize: 16,
                fontWeight: 'bold',
                padding: [6, 0, 0, 10]
              },
              names: {
                color: 'rgba(0,0,0,0.45)',
                fontSize: '12px',
                padding: [10, 0, 0, 0]
              }
            }
          },
          formatter: function (item) {
            return `{val|${chartData}%} \n {names|使用率}`
          } // 显示百分比
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: chartData, name: '数据', itemStyle: { color: chartColor } }, // 主要数据
          {
            value: 100 - chartData,
            name: '空白',
            itemStyle: { color: 'rgba(230,233,247)' }
          } // 灰色部分
        ]
      }
    ],
    tooltip: {
      show: false
      // trigger: 'item',
      // formatter: function(params) {
      //   if (params.name === '数据') {
      //     return params.value + '%';
      //   } else {
      //     return ''; // 空白部分不显示 tooltip
      //   }
      // }
    },
    animation: {
      duration: 0 // 禁用动画效果
    }
  }

  myCharts[key] = echarts.init(chartRef.value);
  myCharts[key].setOption(option)
}
const getQush = () => {
  mAxios.get('vuln/risk/retend').then(res => {
    const xData = res.data.data.map(item => item.date)
    const yData = res.data.data.map(item => item.count)
    var option = {
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: xData
      },
      yAxis: {
        type: 'value'
      },
      tooltip: {
        show: true,
        trigger: 'item'
      },
      series: [
        {
          data: yData,
          name: '漏洞数量',
          type: 'line',
          smooth: true
        }
      ]
    }
    var chartDom = document.getElementById('echartBox')
    var myChart = echarts.init(chartDom)
    myChart.setOption(option)
  })
}
const eveCount = ref(null)
const getEveCount = () => {
  mAxios.get('vuln/eve/count').then(res => {
    eveCount.value = res.data.data
  })
}
const sysTime = ref('')
onMounted(() => {
  sysTime.value = moment().format("YYYY-MM-DD HH:mm:ss")
  getEveCount()
  getQush()
  getDeviceInfo()
  timer.value = setInterval(() => {
    sysTime.value = moment().format("YYYY-MM-DD HH:mm:ss")
    getDeviceInfo()
  }, 5000)
})
// 页面销毁前清除定时器
onBeforeUnmount(() => {
  clearInterval(timer.value)
})

function linkTo(route, param) {
  $router.push({
    path: route,
    query: {
      param
    }
  })
}

const productName = ref()
const productType = ref()
const serialNumber = ref()
const updatedAt = ref()
const getProductionInfo = async () => {
  const { data: res } = await req_getProductionInfo()
  productName.value = res.productName
  productType.value = res.productType
  serialNumber.value = res.serialNumber
}
const getUpdateTime = async () => {
  try {
    const { data: time } = await req_getUpdateTime()
    updatedAt.value = time.updatedAt
  } catch (err) {
    updatedAt.value = ''
  }
}
const getDeviceCount = async () => {
  let result = await req_getDevicesCount()
  let approveParams = {
    type: 0,
    status: 0
  }
  let res = await req_getGuardApproveCount(approveParams)
  if (result.status === 200 && res.status === 200) {
    data.guardCountFrom = { ...result.data, newDeviceCount: res.data }
  }
}
const getGuardHomeInfo = async () => {
  const { data: res } = await req_getGuardHomeInfo()
  data.guardInfoList = res // 存储总数据条数
  guardInfoList.value = res.slice(0, 6) // 初始显示前6条
  if (res.length >= 6) scrollStart() // 滚动数据
}
const getDeviceInfo = async () => {
  function diskSize(num) {
    if (num == 0) return '0 B'
    var k = 1024
    var sizeStr = ['B', 'K', 'M', 'G', 'T', 'PB', 'EB', 'ZB', 'YB']
    var i = 0
    for (var l = 0; l < 8; l++) {
      if (num / Math.pow(k, l) < 1) {
        break
      }
      i = l
    }
    return (num / Math.pow(k, i)).toFixed(0) + sizeStr[i]
  }

  let { data: res } = await mAxios.get("system/info")
  
  data.cpuUsage = res.data.cpuUsage.toFixed(2)
  data.memoryUsage = res.data.memoryUsage.toFixed(2)
  data.diskUsage = res.data.diskUsage.toFixed(2)
  // data.runningTime = res.mwUpTime.days + '天' + res.mwUpTime.hours + '小时' + res.mwUpTime.minutes + '分' + res.mwUpTime.seconds + '秒'
  // data.memoryTotal = diskSize(res.memoryTotal)
  // data.diskTotal = diskSize(res.partitionTotal[0].usage)

  generateRingChart(cpu, 'rgba(91,143,249,0.95)', data.cpuUsage, 'cpu')
  generateRingChart(memory, 'rgba(116,195,121,0.95)', data.memoryUsage, 'memory')
  generateRingChart(disk, 'rgba(118,111,223,0.95)', data.diskUsage, 'disk')
}
const viewEvent = (homeEventTitle, deviceId, osType) => {
  let startTime = ''
  let endTime = ''
  let eventType = 0
  if (homeEventTitle == '本周事件') {
    startTime = moment(getWeekDate().startTime).format('YYYY-MM-DD HH:mm:ss')
    endTime = moment(getWeekDate().endTime).format('YYYY-MM-DD HH:mm:ss')
  } else {
    startTime = moment(new Date().setHours(0, 0, 0, 0)).format('YYYY-MM-DD HH:mm:ss')
    endTime = moment(new Date().setHours(23, 59, 59, 999)).format('YYYY-MM-DD HH:mm:ss')
  }
  if (homeEventTitle == '今日威胁') {
    eventType = 1
  }
  $router.push({
    path: '/auditlog',
    query: {
      homeEventTitle,
      deviceId,
      eventType,
      startTime,
      endTime,
      converge: osType == 'linux' ? 1 : 0
    }
  })
}
// 获取本周的时间间隔
const getWeekDate = () => {
  let now = new Date() // 当前日期
  let nowDayOfWeek = now.getDay() === 0 ? 7 : now.getDay() // 今天本周的第几天
  let nowDay = now.getDate() // 当前日
  let nowMonth = now.getMonth() // 当前月
  let nowYear = now.getYear() // 当前年
  nowYear += nowYear < 2000 ? 1900 : 0 //
  let weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek + 1) // 本周起始时间
  let weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek + 1)) // 本周结束时间
  return {
    startTime: weekStartDate,
    endTime: weekEndDate
  }
}
const viewCurrentPolicy = (deviceId, osType) => {
  linkTo('/program')
  setTimeout(() => {
    nextTick(() => {
      treeStore.osType = osType
      treeStore.treeDeviceId = deviceId
      treeStore.treeLinkedTableRef.getTableData()
    })
  }, 500)
}

eventBus.on('clearMonitorInterval', () => {
  clearInterval(data.timer)
})
</script>

<style lang="scss" scoped>
.chart-box {
  font-family: 'Microsoft YaHei', '微软雅';
  text-align: center;
  margin-right: 58px;
  .chart-style {
    width: 140px;
    height: 140px;
    margin-bottom: 5px;
  }
  .chart-title {
    font-weight: bold;
    font-size: 16px;
    color: #000000;
    line-height: 22px;
  }
}
#Monitor {
  .panel-default {
    padding: 24px;
    padding-bottom: 20px;
    margin-bottom: 16px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 1px 1px 10px 1px #e9e9e9;

    .panel-title {
      font-family: 'Microsoft YaHei', '微软雅';
      font-weight: bold;
      font-size: 20px;
      color: #333333;
      line-height: 28px;
      text-align: left;
      font-style: normal;
      margin-bottom: 21px;
    }
    .panel-header > li:first-child {
      padding-left: 32px;
    }
    .panel-header {
      position: relative;
      height: 54px;
      line-height: 54px;
      border-bottom: 1px solid #e1e1e1;
      display: flex;
      align-items: center;

      li {
        display: inline-block;
        width: 9%;
        font-size: 14px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        padding: 0 10px;
        color: rgba(32, 34, 36, 0.8);
        cursor: default;
      }

      .header-li-0,
      .header-li-7 {
        width: 14%;
      }

      .more {
        position: absolute;
        right: 20px;
        top: 15px;
        width: 30px;
        font-size: 14px;
        padding: 0;

        i {
          color: #059bd5;
          cursor: pointer;
        }
      }
    }

    .statusHead {
      background: #f1f4f9;
      border-radius: 4px;
      border: none !important;
      margin-top: 24px;
      li {
        font-weight: bold;
        font-size: 14px;
        color: #202224;
        line-height: 20px;
        text-align: left;
      }
    }

    .panel_content {
      max-height: 270px;
      overflow: hidden;

      ul {
        li {
          font-size: 14px;

          i {
            color: #4828d2;
            cursor: pointer;
          }

          span {
            display: inline-block;
            width: 64px;
            line-height: 26px;
            text-align: center;
            height: 26px;
            border-radius: 13.5px;
            color: #fff;
            font-size: 14px;
          }

          .green {
            background: #54c571;
          }

          .red {
            background: rgb(255 141 0 / 70%);
          }

          .gray {
            background-color: #bfbfbf;
          }
        }
      }
    }

    .guard,
    .guard > div {
      display: flex;
    }

    .panel-body {
      padding: 0 20px;
      justify-content: space-between;

      .guard {
        align-items: center;
        cursor: pointer;
        margin-top: 10px;
        div {
          flex-direction: column;
          margin-left: 20px;
        }

        img {
          width: 40%;
        }

        .guard-num {
          font-family: Arial, Arial;
          font-weight: bold;
          color: rgba(0, 0, 0, 0.85);
          line-height: 38px;
          text-align: left;
          font-size: 30px;
        }

        .guard-title {
          font-family: 'Microsoft YaHei', '微软雅';
          color: #898787;
          font-weight: 400;
          font-size: 14px;
          color: rgba(0, 0, 0, 0.45);
          line-height: 22px;
          text-align: right;
          font-style: normal;
        }
      }
    }
  }

  .deviceInfo {
    margin-bottom: 0;
    background: linear-gradient(to bottom, rgb(255, 255, 255) 60%, rgb(187, 194, 255) 200%);
  }

  .event-content {
    .content-hearder {
      display: flex;
      justify-content: space-between;
    }

    .filter {
      width: 40%;

      .filter-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;

        :deep(.el-select),
        :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
          width: 65%;
        }
      }

      .equipment {
        :deep(.el-input) {
          width: 65%;
        }
      }
    }
  }

  .device-info {
    display: flex;
    justify-content: space-between;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.85);
    ul {
      width: 43%;
      padding-left: 20px;

      li {
        line-height: 28px;
        span {
          display: inline-block;
          margin-right: 5px;
          max-width: 400px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    .demo-progress {
      display: flex;
      align-items: center;

      :deep(.el-progress--circle, .el-progress--dashboard) {
        margin-right: 160px;
      }

      .percentage-label {
        display: block;
        width: 125px;
        font-size: 16px;
        font-weight: bold;
        line-height: 22px;
        color: #000;
        margin-top: -25px;
        margin-bottom: 5px;
        margin-left: 100px;
        text-align: left;
      }

      .percentage-value {
        position: relative;
        margin-bottom: 0;
        color: #000;
        font-size: 16px;
        line-height: 22px;
        font-weight: bold;
        margin-left: 100px;

        i {
          position: absolute;
          top: 25px;
          left: 0;
          display: block;
          width: 150px;
          text-align: left;
          font-size: 12px;
          font-weight: 300;
        }
      }
    }

    .device-img {
      position: relative;
      width: 15%;

      img {
        position: absolute;
        top: -5px;
        right: 0;
      }
    }
  }
}
</style>
